package com.example.stlink.activitys.fragmentChild.activityUserInfo;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;

import com.example.stlink.R;
import com.example.stlink.model.constants.ModelFieldConstants;
import com.example.stlink.model.constants.UrlConstants;
import com.example.stlink.model.response.BaseResponse;
import com.example.stlink.utils.httpUtils.PostBodyParamHttpUtils;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.textfield.TextInputEditText;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Objects;

public class ModifyUserInfo extends AppCompatActivity {

    private TextView abTvTitle;
    private ImageView abIvTitle;
    private AppCompatButton abBtSave;
    private TextInputEditText tiNewMsg;

    private Handler handler;
    private Bundle bundle;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_modify_user_info);

        initView();
    }


    /**
     * 初始胡布局
     */
    private void initView(){
        abTvTitle = findViewById(R.id.ab_tv_title);
        abIvTitle = findViewById(R.id.ab_iv_title);
        abBtSave = findViewById(R.id.ab_bt_save);
        tiNewMsg = findViewById(R.id.ti_new_msg);

        refreshData();
        //设置监听器
        setListener();
    }

    /**
     * 刷新数据
     */
    private void refreshData(){
        bundle = getIntent().getExtras();
        String toBeModify = (String) bundle.get(ModelFieldConstants.TO_BE_MODIFY);
        switch (toBeModify){
            case ModelFieldConstants.USER_NAME : {
                abTvTitle.setText("更换昵称");
                String userName = (String) bundle.get(ModelFieldConstants.USER_NAME);
                if(userName != null){
                    tiNewMsg.setText(userName);
                }else{
                    tiNewMsg.setText("");
                }
                if(tiNewMsg.getText() != null){
                    tiNewMsg.setSelection(tiNewMsg.getText().length());
                }
                break;
            }
            case ModelFieldConstants.COLLEGE_NAME : {
                abTvTitle.setText("更换大学");
                String schoolName = (String) bundle.get(ModelFieldConstants.COLLEGE_NAME);
                if(schoolName != null){
                    tiNewMsg.setText(schoolName);
                }else{
                    tiNewMsg.setText("");
                }
                if(tiNewMsg.getText() != null){
                    tiNewMsg.setSelection(tiNewMsg.getText().length());
                }
                break;
            }
            case ModelFieldConstants.REAL_NAME : {
                abTvTitle.setText("真实姓名验证");
                String realName = (String) bundle.get(ModelFieldConstants.REAL_NAME);
                if(realName != null){
                    tiNewMsg.setText(realName);
                }else{
                    tiNewMsg.setText("");
                }
                if(tiNewMsg.getText() != null){
                    tiNewMsg.setSelection(tiNewMsg.getText().length());
                }
                break;
            }
            case ModelFieldConstants.ID_NUMBER : {
                if ((bundle.getInt(ModelFieldConstants.ROLE_ID) == 0)) {
                    abTvTitle.setText("更换学号");
                } else {
                    abTvTitle.setText("更换工号");
                }
                Long idNumber = (Long) bundle.get(ModelFieldConstants.ID_NUMBER);
                if(idNumber != null){
                    tiNewMsg.setText(String.valueOf(idNumber));
                }else{
                    tiNewMsg.setText("");
                }
                if(tiNewMsg.getText() != null){
                    tiNewMsg.setSelection(tiNewMsg.getText().length());
                }
                break;
            }
            case ModelFieldConstants.GENDER : {
                //修改性别的时候，不能单纯的输入了，无法保证用户的输入内容，所以采用对话框的形式
                abTvTitle.setText("更换性别");
                Boolean sex = (Boolean) bundle.get(ModelFieldConstants.GENDER);
                if(sex != null){
                    if(sex){
                        tiNewMsg.setText("男");
                    }else{
                        tiNewMsg.setText("女");
                    }
                }
                //禁止编辑
                tiNewMsg.setFocusableInTouchMode(false);
                //不可粘贴，长按不会弹出粘贴框
                tiNewMsg.setKeyListener(null);


                tiNewMsg.setOnClickListener(v -> {
                    System.out.println("choose gender............");
                    String[] singleItems = {"男", "女"};
                    int checkedItem = 0;
                    if(tiNewMsg.getText() != null){
                        checkedItem = "男".equals(tiNewMsg.getText().toString()) ? 0 : 1;
                    }

                    MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(ModifyUserInfo.this)
                        .setTitle("请选择性别")
                        .setNeutralButton(getString(R.string.cancel), (dialog, which) -> {

                        })
                        .setPositiveButton(getString(R.string.ok), (dialog, which) ->
                                tiNewMsg.setText(singleItems[bundle.getInt("checkedItem")]))
                        .setSingleChoiceItems(singleItems, checkedItem, (dialog, which) ->
                                bundle.putInt("checkedItem", which));
                    materialAlertDialogBuilder.show();
                });
                break;
            }
            case ModelFieldConstants.EMAIL : {
                abTvTitle.setText("更换邮箱");
                String email = (String) bundle.get(ModelFieldConstants.EMAIL);
                if(email != null){
                    tiNewMsg.setText(email);
                }else{
                    tiNewMsg.setText("");
                }
                if (tiNewMsg.getText() != null){
                    tiNewMsg.setSelection(tiNewMsg.getText().length());
                }
                break;
            }
            case ModelFieldConstants.PHONE : {
                abTvTitle.setText("更换电话号码");
                String phone = (String) bundle.get(ModelFieldConstants.PHONE);
                if(phone != null){
                    tiNewMsg.setText(phone);
                }else{
                    tiNewMsg.setText("");
                }
                if(tiNewMsg.getText() != null){
                    tiNewMsg.setSelection(tiNewMsg.getText().length());
                }
                break;
            }
            default:{
                String errorText = "error.....";
                tiNewMsg.setText(errorText);
            }
        }
    }

    /**
     * 实时的监听文本框输入情况
     */
    private void setListener(){
        //返回上一个活动，也就是个人信息部分
        abIvTitle.setOnClickListener(v -> finish());
        tiNewMsg.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            //当输入框文本发生修改时，启动保存按钮，并且为按钮绑定点击监听事件
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //启用保存按钮
                abBtSave.setEnabled(true);
                //修改按钮样式选择器
                abBtSave.setBackgroundResource(R.drawable.selector_bottom_modify_info_save_2);
                abBtSave.setTextColor(Color.WHITE);
                //为按钮添加点击事件
                abBtSave.setOnClickListener(v -> dialog());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    /**
     * 确认对话框
     */
    private void dialog(){

        //添加取消
        AlertDialog alertDialog2 = new AlertDialog.Builder(this)
            .setMessage("请确认是否进行" + abTvTitle.getText())
            .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    modifyInfo();
                    handler = new Handler(Looper.getMainLooper()){
                        @Override
                        public void handleMessage(@NonNull Message msg) {
                            super.handleMessage(msg);
                            Toast.makeText(ModifyUserInfo.this, msg.obj.toString(), Toast.LENGTH_SHORT).show();
                        }
                    };
                }
            })
            .setNegativeButton("取消", (dialogInterface, i) -> {
            })
            .create();
        alertDialog2.show();
    }

    /**
     * 更新信息网络请求
     */
    private void modifyInfo(){
        new Thread(() -> {
            JSONObject jsonObject = new JSONObject();
            boolean isLegalInput = false;
            try {
                jsonObject.put(ModelFieldConstants.ID, (Long) bundle.get(ModelFieldConstants.ID));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            //根据上一个活动传递过来的选择字段，来选择对应的传输方法
            String modifyField = (String) bundle.get(ModelFieldConstants.TO_BE_MODIFY);
            switch (modifyField){
                case ModelFieldConstants.ID_NUMBER:
                case ModelFieldConstants.IN_SCHOOL_TIME:{
                        try {
                            Long msg = Long.parseLong(Objects.requireNonNull(tiNewMsg.getText()).toString());
                            jsonObject.put(modifyField, msg);
                            bundle.putLong(modifyField, msg);
                            isLegalInput = true;
                        }catch (NumberFormatException e){
                            e.printStackTrace();
                            Message msg = new Message();
                            msg.obj = "输入非法.";
                            handler.sendMessage(msg);
                        }catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                }
                case ModelFieldConstants.GENDER:{
                    try {
                        String msg = Objects.requireNonNull(tiNewMsg.getText()).toString();
                        if("男".equals(msg) || "女".equals(msg)){
                            Boolean msgBoolean = "男".equals(msg);
                            jsonObject.put(modifyField, msgBoolean);
                            bundle.putBoolean(modifyField, msgBoolean);
                            isLegalInput  = true;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                }
                case ModelFieldConstants.PHONE: {
                    try {
                        String msg = Objects.requireNonNull(tiNewMsg.getText()).toString();
                        //判断输入电话号码是否能解析为long型，能解析的话说明输入没有非法字符
//                        Long msgLong = Long.parseLong(msg);
                        jsonObject.put(modifyField, msg);
                        bundle.putString(modifyField, msg);
                        isLegalInput = true;
                    }catch (NumberFormatException e){
                        e.printStackTrace();
                        Message msg = new Message();
                        msg.obj = "输入非法.";
                        handler.sendMessage(msg);
                    }catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                }
                case ModelFieldConstants.EMAIL:{
                    Message message = new Message();
                    try {
                        String msg = Objects.requireNonNull(tiNewMsg.getText()).toString();
                        String[] msgStr = msg.split("@");
                        //必须得包含@符号
                        if(msgStr.length == 2){
                            //邮箱的两部分必定是长度大于0的
                            if(msgStr[0].length() > 0 && msgStr[1].length() > 0){
                                jsonObject.put(modifyField, msg);
                                bundle.putString(modifyField, msg);
                                isLegalInput = true;
                            }else{
                                message.obj = "输入非法.";
                                handler.sendMessage(message);
                            }
                        }else{
                            message.obj = "输入非法.";
                            handler.sendMessage(message);
                        }
                    } catch (NumberFormatException e){
                        e.printStackTrace();
                        message.obj = "输入非法.";
                        handler.sendMessage(message);
                    }catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                }
                default:{
                    try {
                        String msg = Objects.requireNonNull(tiNewMsg.getText()).toString();
                        jsonObject.put(modifyField, msg);
                        bundle.putString(modifyField, msg);
                        isLegalInput = true;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
            System.out.println( "jsonObject : " + jsonObject + "..............................");
            String json = jsonObject.toString();
            String url = UrlConstants.USER_UPDATE;

            if(isLegalInput){
                new PostBodyParamHttpUtils() {
                    @Override
                    public void nextMethod(BaseResponse<Object> baseResponse) {
                        Intent intent = new Intent();
                        intent.putExtras(bundle);
                        setResult(RESULT_OK,intent);
                        finish();
                    }
                    @Override
                    public void failedMethod(BaseResponse<Object> baseResponse) {
                        Message message = new Message();
                        System.out.println("修改失败.......................");
                        handler.sendMessage(message);
                    }
                }.postConnect(url, json);
            }
        }).start();
    }
}
